package edu.nf.project.services.storeOperation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.convention.CustomerInfo;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.CustomerOrder;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.CustomerOrderItem;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.PayHistory;
import edu.nf.project.entitys.enums.storeOperation.OrderStatusEnum;
import edu.nf.project.mappers.employeeAndCustomerInformation.convention.CustomerInfoMapper;
import edu.nf.project.mappers.storeOperation.convention.CustomerOrderItemMapper;
import edu.nf.project.mappers.storeOperation.convention.CustomerOrderMapper;
import edu.nf.project.mappers.storeOperation.convention.PayHistoryMapper;
import edu.nf.project.services.exception.derivedAnomalies.CustomerOrderException;
import edu.nf.project.services.storeOperation.PayHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 支付记录 Service 实现类
 */
@Service
public class PayHistoryServiceImpl implements PayHistoryService {
    @Autowired
    private PayHistoryMapper payHistoryMapper;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerOrderMapper customerOrderMapper;

    @Autowired
    private CustomerOrderItemMapper customerOrderItemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean newHistory(PayHistory payHistory) {
        // 只校验会员卡余额
        if (payHistory.getPay_way() == 1) { // 1表示会员卡支付
            LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CustomerInfo::getUId, payHistory.getU_id());
            CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);
            if (customerInfo == null) {
                throw new CustomerOrderException(50010, "会员信息不存在");
            }
            if (customerInfo.getSurplus().compareTo(payHistory.getPay_amount()) < 0) {
                throw new CustomerOrderException(50011, "会员卡余额不足");
            }
        }

        // 插入支付记录
        int result = payHistoryMapper.insert(payHistory);
        if (result <= 0) {
            throw new CustomerOrderException(50009, "添加支付记录失败");
        }

        // 会员卡支付时扣款
        if (payHistory.getPay_way() == 1) {
            BigDecimal newSurplus = customerInfoMapper.selectOne(
                new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getUId, payHistory.getU_id())
            ).getSurplus().subtract(payHistory.getPay_amount());
            LambdaUpdateWrapper<CustomerInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CustomerInfo::getUId, payHistory.getU_id())
                        .set(CustomerInfo::getSurplus, newSurplus);
            result = customerInfoMapper.update(null, updateWrapper);
            if (result <= 0) {
                throw new CustomerOrderException(50012, "扣除会员卡余额失败");
            }
        }

        // 更新订单状态为已支付
        CustomerOrder updateOrder = new CustomerOrder();
        updateOrder.setOrderId(payHistory.getOrder_id());
        updateOrder.setOrderStatus(OrderStatusEnum.PAID);
        updateOrder.setPaymentTime(new Date());
        result = customerOrderMapper.updateById(updateOrder);
        if (result <= 0) {
            throw new CustomerOrderException(50013, "更新订单状态失败");
        }

        return true;
    }

    @Override
    public List<PayHistory> getHistory(Integer u_id) {
        LambdaQueryWrapper<PayHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PayHistory::getU_id, u_id);
        return payHistoryMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addOrderItems(List<CustomerOrderItem> items) {
        if (items == null || items.isEmpty()) {
            throw new CustomerOrderException(50014, "订单项列表不能为空");
        }
        int successCount = 0;
        for (CustomerOrderItem item : items) {
            int result = customerOrderItemMapper.insert(item);
            if (result > 0) {
                successCount++;
            }
        }
        if (successCount != items.size()) {
            throw new CustomerOrderException(50015, "部分订单项添加失败");
        }
        return true;
    }
}
